'use strict';

/**
 * Created by twer on 15/2/24.
 */
angular.module('blog')
    .controller('BlogRecycleCtrl', [
        '$scope',
        '$rootScope',
        '$routeParams',
        'BlogRecycleQueryService',
        'BlogRecycleManageService',
        'BlogDetailService',
        'PathSuffixConstant',
        function ($scope, $rootScope, $routeParams, BlogRecycleQueryService, BlogRecycleManageService, BlogDetailService, PathSuffixConstant) {
            $rootScope.visitedUserId = $routeParams.userId;
            var author = $routeParams.userId;

            /**
             * 查询回收站的blog
             */
            $scope.query = function() {
                BlogRecycleQueryService.query({author: author + PathSuffixConstant}, function (response) {
                    $scope.blogs = response.results;
                });
            };

            /**
             * 从回收站里恢复
             *
             * @param blogId
             */
            $scope.restoreFromRecycle = function(blogId) {
                BlogRecycleManageService.restore({blogId: blogId}, function() {
                    reloadRecycleBlogs(blogId);
                });
            };

            /**
             * 完全删除
             *
             * @param blogId
             */
            $scope.deleteCompleted = function(blog) {
                if (confirm('是否完全删除' + blog.title + '？删除后不能恢复。')) {
                    BlogDetailService.remove({blogId: blog._id}, function() {
                        reloadRecycleBlogs(blog._id);
                    });
                }
            };

            $scope.query();

            /**
             * 静态load
             *
             * @param deletedId
             */
            function reloadRecycleBlogs(deletedId) {
                var newBlogs = [];
                angular.forEach($scope.blogs, function(v) {
                    if (v._id != deletedId) {
                        newBlogs.push(v);
                    }
                });
                $scope.blogs = newBlogs;
            }
        }]);
